<template lang="pug">
a.audio(
  title="麦克风"
  :class="{x:!config.audio}"
  :style="'--vol:' + vol + '%'"
)
</template>

<script lang="coffee">
import config from '~/store/record.coffee'
import media_by_id from '~/lib/media_by_id.coffee'
export default {
setup:=>
  vol = ref 0
  interval = undefined
  disconnect = undefined

  clear = =>
    if disconnect
      clearInterval interval
      disconnect()
      disconnect = undefined
    return

  onBeforeUnmount clear
  watchEffect =>
    clear()

    {audio} = config
    if not audio
      return

    ###
    基于Web Audio API实现音频可视化效果 - Web API 接口参考 | MDN : https://t.cn/RqRYrFg
    AnalyserNode.smoothingTimeConstant - Web API 接口参考 | MDN : https://t.cn/Rxwr0Dj
    ###

    stream = await media_by_id.audio audio
    ac = new AudioContext
    source = ac.createMediaStreamSource stream
    analyser = ac.createAnalyser()
    analyser.minDecibels = -90
    analyser.maxDecibels = -10
    #analyser.smoothingTimeConstant = 0.85
    analyser.fftSize = 32

    disconnect = =>
      #analyser.disconnect(ac.destination)
      source.disconnect analyser
      ac.close()

    bufferLength = analyser.frequencyBinCount
    dataArray = new Uint8Array(bufferLength)

    interval = setInterval(
      =>
        analyser.getByteFrequencyData(dataArray)
        vol.value = Math.round((Math.min 1, Math.max(...dataArray)/200)*100)
        return
      100
    )
    source.connect analyser
    # 再连接至扬声器播放
    #analyser.connect(ac.destination)

    return
  {
    vol
    config
  }
}
</script>

<style lang="stylus" scoped>
a
  overflow hidden
  &:after
    height var(--vol)
    transition all 0.2s
    content ''
    mix-blend-mode darken
    background #A1E1EE
    width 100%
    position absolute
    bottom 0

  &.x:after
    display none
</style>
